<template>
  <div>
    <TableSearch :query="query" :options="searchOpt" :search="handleSearch"/>
    <div class="container">
      <TableCustom
          :columns="columns"
          :tableData="tableData"
          :total="page.total"
          :viewFunc="handleView"
          :view-func2="handleView2"
          :delFunc="handleDelete"
          :page-change="changePage"
          :editFunc="handleEdit"
      >
        <template #toolbarBtn>
          <el-button type="warning" :icon="CirclePlusFilled" @click="visible = true">新增</el-button>
        </template>
      </TableCustom>
    </div>
    <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="700px" destroy-on-close
               :close-on-click-modal="false" @close="closeDialog">
      <TableEdit
          :form-data="rowData"
          :options="options"
          :edit="isEdit"
          :update="isEdit ? handleUpdate : handleAdd"
      />
    </el-dialog>
    <el-dialog title="查看源代码文件" v-model="visible1" width="700px" destroy-on-close>
      <FileViewer/>
    </el-dialog>
    <el-dialog title="查看缺陷报告" v-model="visible2" width="700px" destroy-on-close>
      <ReportViewer/>
    </el-dialog>

  </div>
</template>

<script setup lang="ts" name="system-projects">
import {onMounted, reactive, ref} from 'vue';
import {ElMessage} from 'element-plus';
import {CirclePlusFilled} from '@element-plus/icons-vue';
import {Projects} from '@/types/project';
import TableCustom from '@/components/table-custom.vue';
import TableSearch from '@/components/table-search.vue';
import {FormOption, FormOptionList} from '@/types/form-option';
import axios from 'axios';
import FileViewer from "@/views/system/file-viewer.vue";
import ReportViewer from "@/views/system/report_viewer.vue";
import {FileInfo} from "@/types/file";


// 查询相关
const query = reactive({
  name: '',
});
const searchOpt = ref<FormOptionList[]>([
  {type: 'input', label: '项目名称：', prop: 'name'}
])
const handleSearch = () => {
  changePage(1);
};

// 表格相关
let columns = ref([
  {type: 'index', label: '序号', width: 55, align: 'center'},
  {prop: 'name', label: '项目名称'},
  {prop: 'username', label: '创建人'},
  {
    prop: 'has_src',
    label: '是否上传源代码',
    formatter: (row: any) => {
      return row.has_src ? '是' : '否';
    }
  },
  {
    prop: 'has_report', label: '是否上传缺陷报告',
    formatter: (row: any) => {
      return row.has_report ? '是' : '否';
    }
  },
  {
    prop: 'has_file_model', label: '是否文件级训练', formatter: (row: any) => {
      return row.has_file_model ? '是' : '否';
    }
  },
  {
    prop: 'has_sen_model', label: '是否语句级训练', formatter: (row: any) => {
      return row.has_sen_model ? '是' : '否';
    }
  },
  {prop: 'create_at', label: '创建时间'},
  {prop: 'operator', label: '操作', width: 400},
])
const page = reactive({
  index: 1,
  size: 10,
  total: 0,
})

const globalApiUrl = import.meta.env.VITE_API_URL

console.log('Global API URL:', globalApiUrl);

const projectsUrl = globalApiUrl + '/projects';

const tableData = ref<Projects[]>([]);
const getData = async () => {
  // 向后端请求获取projects
  axios.get(projectsUrl, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authorization': 'Bearer ' + localStorage.getItem('access_token')
    },
    params: {
      page: page.index,
      size: page.size,
      name: query.name,
    }
  }).then((response) => {
    tableData.value = response.data.data.data;
    page.total = response.data.data.total;
    console.log(response.data.data)
  })
};
// 页面加载时调用 getData
onMounted(() => {
  getData();
});
const changePage = (val: number) => {
  page.index = val;
  console.log('Current Page:', page.index);
  getData();
};

// 新增/编辑弹窗相关
let options = ref<FormOption>({
  labelWidth: '100px',
  span: 12,
  list: [
    {type: 'input', label: '项目名称', prop: 'name', required: true},
  ]

})
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});
const handleEdit = (row: Projects) => {
  rowData.value = {...row};
  isEdit.value = true;
  visible.value = true;
  console.log(row);
};

// 新增操作
const handleAdd = async (formData: any) => {
  try {
    const response = await axios.post(projectsUrl, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
    });

    if (response.data.result) {
      ElMessage.success('新增项目成功');
      // 关闭弹窗
      closeDialog();
      // 刷新数据
      getData();
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error('新增失败，请稍后重试');
  }
};
// 编辑操作
const handleUpdate = async (formData: any) => {
  try {
    const response = await axios.put(projectsUrl, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
    });

    if (response.data.result) {
      ElMessage.success('编辑项目成功');
      // 关闭弹窗
      closeDialog();
      // 刷新数据
      getData();
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error('编辑失败，请稍后重试');
  }
};

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
  visible1.value = false;
  visible2.value = false;
};

// 查看详情弹窗相关
const visible1 = ref(false);
const visible2 = ref(false);

const filesUrl = globalApiUrl + '/files'; // 后端获取文件夹的 URL
// 获取源代码文件文件列表
let fileList = ref([]); // 当前目录下的文件列表
const handleView = async (row: FileInfo) => {
  try {
    const response = await axios.get(filesUrl, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      params: {path: row.id + '/src'} // 传递当前路径
    });
    fileList = response.data.data;
    localStorage.setItem('srcFileList', JSON.stringify(fileList));
    localStorage.setItem('srcCurrentPath', row.id + '/src');
  } catch (error) {
    console.error('Error fetching file list:', error);
  }
  visible1.value = true;
};
// 获取缺陷报告列表
const handleView2 = async (row: FileInfo) => {
  try {
    const response = await axios.get(filesUrl, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      params: {path: row.id + '/report'} // 传递当前路径
    });
    fileList = response.data.data;
    localStorage.setItem('reportFileList', JSON.stringify(fileList));
    localStorage.setItem('reportCurrentPath', row.id + '/report');
  } catch (error) {
    console.error('Error fetching file list:', error);
  }
  visible2.value = true;
};

// 删除相关
const handleDelete = (row: Projects) => {
  // 向后端请求删除
  axios.delete(projectsUrl, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authorization': 'Bearer ' + localStorage.getItem('access_token')
    },
    params: {
      id: row.id
    }
  }).then((response) => {
    if (response.data.result) {
      ElMessage.success('删除成功');
    } else {
      ElMessage.error("删除失败，请稍后重试");
    }
    getData();
  })
}
</script>

<style scoped></style>

<style scoped>
.icon-check {
  color: green;
}

.icon-close {
  color: red;
}
</style>


